package orchestration.android.execution.tasks;

import orchestration.android.RunExecutionActivity;
import orchestration.android.execution.commands.CommandFactory;
import orchestration.android.execution.exceptions.TaskExecutionException;
import orchestration.persistence.exceptions.UnsupportedTypeException;
import android.content.Intent;
import android.content.pm.PackageManager;

/**
 * @author  <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 */
public class ServiceStartStopTask extends AndroidTask {

	/**
	 * @uml.property  name="intent"
	 */
	private Intent intent;
	/**
	 * @uml.property  name="start"
	 */
	private boolean start;
	
	public ServiceStartStopTask(String id) {
		super(id);
	}

	
	@Override
	public void onExecute(RunExecutionActivity rea) throws TaskExecutionException {
		if(rea.getPackageManager().queryIntentServices(intent, PackageManager.GET_RESOLVED_FILTER).size()==0)
			throw new TaskExecutionException("Cannot find services to handle the intent");
		try {
			fillIntentExtras(rea,intent);
		} catch (UnsupportedTypeException e) {
			throw new TaskExecutionException(e);
		}
		boolean noError=true;
		if(start){
			noError=rea.startService(intent)!=null;
		}else{
			noError=rea.stopService(intent);
		}
		if(!noError){
			throw new TaskExecutionException("Error trying to start or stop a service");
		}
		rea.setCurrentCommand(CommandFactory.createCommand(CommandFactory.RESUME_EXECUTION));
		rea.executeNextCommand();
	}

	/**
	 * @param intent
	 * @uml.property  name="intent"
	 */
	public void setIntent(Intent intent) {
		this.intent = intent;
	}

	/**
	 * @return
	 * @uml.property  name="intent"
	 */
	public Intent getIntent() {
		return intent;
	}


	/**
	 * @return
	 * @uml.property  name="start"
	 */
	public boolean isStart() {
		return start;
	}


	/**
	 * @param start
	 * @uml.property  name="start"
	 */
	public void setStart(boolean start) {
		this.start = start;
	}

}
